﻿using Newtonsoft.Json;
using Project.Core.Config.Common.Filter;
using Project.Core.Config.Entity.Dto;
using Project.Core.Config.Service.Impl;
using Project.Core.Test.Entity;
using Project.Core.Test.Entity.Input;
using Project.Core.Test.Mapper;
using System.Diagnostics;

namespace Project.Core.Test.Service.Impl {
    public class SysUserServiceImpl : ServiceImpl<SysUserMapper, SysUser, int>, SysUserService {
        public SysUser GetByUsername(string name) {
            return BaseMapper.GetByName(name);
        }

        public UserLoginDto Login(string username, string password) {
            Debug.WriteLine("验证用户名和密码");
            var user = BaseMapper.GetByUsernameAndPassword(username, password);
            if (user == null) {
                throw new UserLoginException("用户名或者密码不正确!");
            }
            Debug.WriteLine("账号:" + user.UserName);
            Debug.WriteLine("密码:" + user.Password);

            user.LastLogin = DateTime.Now;
            BaseMapper.Update(user);

            var role = BaseMapper.GetUserPremById(user.Id);
            Debug.WriteLine(JsonConvert.SerializeObject(role));

            return new UserLoginDto(user.Id, user.UserName, role);
        }

        public UserLoginDto Login(string username) {
            var user = BaseMapper.GetByName(username);
            if (user == null) {
                return null;
            } else {
                var role = BaseMapper.GetUserPremById(user.Id);
                return new UserLoginDto(user.Id, user.UserName, role);
            }
        }

        public bool Register(SysUser user) {
            if (BaseMapper.GetByName(user.UserName) == null) {
                BaseMapper.Add(user);
                return true;
            } else {
                return false;
            }
        }

        public bool Repass(SysUserRepassInput repassInput) {
            return BaseMapper.Repass(repassInput);
        }
    }
}
